import Sequelize from 'sequelize';
import express from 'express';
import { statusList, sequelizeStatus } from '../../common/status'; // 状态码对照
import { Order, Item, Sku } from '../../modal/index'; // 数据库实体类
import { checkPermission, createOrderNumber } from '../../utils/utils'; // 工具类

const router = express.Router();
const permission = ["all"];

router.post('/', async function (Request, Response, next) {
  // Item.Modal.sync()
  //权限校验
  await checkPermission(Request, Response, permission)
  let param = Request.body;
  let price = 0; // 支付金额
  param.skuAttr = JSON.stringify(param.skuAttr);
  await getSkusByItemId(param.itemId, Response).then(res => {
    // 根据传来的SKU计算商品应付价格
    let itemDetail = res;
    param.itemName = itemDetail.itemName; // 商品名
    param.itemMainImg = itemDetail.itemMainImg;
    itemDetail.skus.some(item => {
      let skuAttr1 = item.skuAttr; // 数据库sku集合
      let skuAttr2 = param.skuAttr; // 选中的sku集合
      if (skuAttr1 === skuAttr2) {
        // 修改传参过来的字段
        param.singlePrice = item.price;
        param.price = param.quantity * item.price;
      }
    });
  })
  // 构造订单表相关数据
  param.orderNumber = createOrderNumber();
  param.status = 1;
  Order.Modal.create(param).then(res => {
    if (res && res.id) {
      let itemId = res.id
      // 更新订单成功
      console.log('更新订单成功')
      Response.json({
        data: res,
        message: "success"
      });
    } else {
      Response.status(300).send({ message: "商品查询失败" });
    }
  }).catch(err => {
    console.log(err)
    Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
  });
});

function getSkusByItemId(itemId, Response) {
  // 根据itemId查询SKU
  return new Promise((resolve, reject) => {
    Item.Modal.findAll({
      where: {
        id: itemId,
      },
      include: [{
        model: Sku.Modal,
        as: 'skus'
      }], // 表关联
      distinct: true //去重，表关联时需要
    }).then(res => {
      if (res && res.length > 0) {
        // let data = res[0]
        // data.skus = toJson(data.skus, ["skuAttr"])
        // Response.json({
        //   data: {
        //     itemDetail: res[0],
        //   },
        //   message: "success"
        // });
        resolve(res[0])
      } else {
        Response.status(300).send({ message: "商品查询失败" });
      }
    }).catch(err => {
      console.log(err)
      Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
    });
  })
}

module.exports = router;